package com.study.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;

@WebServlet("/upload")
@MultipartConfig // 启用文件上传功能，文件上传必加

public class Upload extends HttpServlet {
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("text/html;charset=UTF-8");
		System.out.println("Upload servlet begin to service");
		
		req.setCharacterEncoding("UTF-8"); // 设置请求编码
		
		// 获取普通表单参数
		String myNane = req.getParameter("myNane"); // 获取请求表单参数，表单name定义的字段
		System.out.println(myNane);
		
		// 获取Part对象，用于处理文件上传
		Part part = req.getPart("myFile"); // 获取请求表单中上传文件的Part对象，表单name定义的字段
		// 获取文件名
		String fileName = part.getSubmittedFileName();
		System.out.println(fileName);
		// 获取文件存放路径
		String filePath = req.getServletContext().getRealPath("/");
		System.out.println(filePath);
		// 保存文件到指定路径
		part.write(filePath + fileName);
		System.out.println("Upload servlet end to service");
	}
}
